//
//  UIImage+LZCompression.m
//  laziz_Consumer
//
//  Created by xbn_iMac on 2016/11/30.
//  Copyright © 2016年 XBN. All rights reserved.
//

#import "UIImage+LZCompression.h"

@implementation UIImage (LZCompression)

/**
 *  压缩图片到指定大小并且返回图片数据
 *
 *  @param aSize 指定图片尺寸大小
 *
 *  @param maxFileSize 指定大小
 *
 *  @return 图片数据
 */
- (NSData *)compressionImageToDataFrameSize:(CGSize)aSize maxFileSize:(NSInteger)maxFileSize
{
    UIImage *newImage = self;
    
    if (!CGSizeEqualToSize(aSize, CGSizeZero)) {
        //缩
        CGSize newSize = CGSizeMake(self.size.width, self.size.height);
        CGFloat tempHeight = newSize.height / aSize.height;
        CGFloat tempWidth = newSize.width / aSize.width;
        if (tempWidth > 1.0 && tempWidth > tempHeight) {
            newSize = CGSizeMake(self.size.width / tempWidth, self.size.height / tempWidth);
        }
        else if (tempHeight > 1.0 && tempWidth < tempHeight){
            newSize = CGSizeMake(self.size.width / tempHeight, self.size.height / tempHeight);
        }
        UIGraphicsBeginImageContext(newSize);
        [self drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
        newImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }
    
    //压
    CGFloat compression = 0.9f;
    CGFloat maxCompression = 0.1f;
    NSData *imageData = UIImageJPEGRepresentation(newImage, compression);
    while (imageData.length / 1000 > maxFileSize && compression > maxCompression) {
        compression -= 0.1;
        imageData = UIImageJPEGRepresentation(newImage, compression);
    }
    
    return imageData;
}

@end
